package controllers;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import models.Userlogin;
import javax.servlet.http.HttpServletRequest;
import rbac.RbacService;
import rbac.impl.DefaultRbacService;
import rbac.models.Menu;
import rbac.models.User;
import rbac.models.Config;


import com.et.ar.ActiveRecordBase;
import com.et.mvc.Controller;
import com.et.mvc.JsonView;
import com.et.mvc.MultipartFile;
import com.et.mvc.View;
import com.et.mvc.binding.DataBinders;
import com.et.mvc.filter.BeforeFilter;
import com.et.mvc.filter.BeforeFilters;

@BeforeFilters( { @BeforeFilter(execute = "initRbac"),
		@BeforeFilter(execute = "checkUserPrivilege"),
		@BeforeFilter(execute = "getConfigs"),
		@BeforeFilter(execute = "initMenus", only = { "index" }) })
public class ApplicationController extends Controller {
	static {
		DataBinders.setAllowEmpty(true);
	}

	public static String join(String[] items) {
		String s = "";
		for (String item : items) {
			s += item + ",";
		}
		return s.substring(0, s.length() - 1);
	}

	protected boolean getConfigs() throws Exception {
		//读取个人的配置文件
		User user = null;
		if (rbac != null)
		  user = (User) rbac.getCurrentUser();
		String cfgtype = "system";
		boolean bpercfg = false;
		if (user != null) {
			bpercfg = true;
			cfgtype = user.getLogin();
		}
		List<Config> configs = Config.findAll(Config.class, "cfgtype=?", new Object[]{ cfgtype });
		if (configs.size() == 0){
			bpercfg = false;
			configs = Config.findAll(Config.class, "cfgtype='system'", null);
		}
		
		
		Map<String, Object> cfgs = new HashMap<String, Object>();
		//Cfg cfg = new Cfg();
		for (Config item : configs) {
			String itemkey = item.getCfgcode();
			if (bpercfg){
				int i = user.getLogin().length();
				itemkey = itemkey.substring(i);
			}
			cfgs.put(itemkey,item.getCfgkeyvalue());
			/**if (item.getCfgcode().equals("theme"))
				cfg.setTheme(item.getCfgkeyvalue());
			if (item.getCfgcode().equals("menuselect"))
				cfg.setTheme(item.getCfgkeyvalue());
			if (item.getCfgcode().equals("menulayout"))
				cfg.setTheme(item.getCfgkeyvalue());**/
		}
		
		request.setAttribute("cfgs", cfgs);	
		return true;
	}

	protected String getAllowedUrl(int id) throws Exception {
		List<Menu> menus = Menu.findAll(Menu.class, "parentid=?",
				new Object[] { id }, "sort");

		for (Menu menu : menus) {
			if (rbac.isAllowed(menu.getUrl()) == true) {
				return menu.getUrl();
			}

		}
		return "";
	}

	protected boolean initMenus() throws Exception {
		List<Menu> menus = Menu.findAll(Menu.class, null, null, "sort");
		for (Menu menu : menus) {
			if (menu.getVisable() == 0) {
				if ((rbac.isAllowed(menu.getUrl()) == true) && (menu.getParentid() != 0)) {
					menu.setVisable(1);
				} else {
					String newurl = getAllowedUrl(menu.getId());
					if (!newurl.equals("")) {
						menu.setVisable(1);
						menu.setUrl(newurl);
					}
				}
			}

		}
		request.setAttribute("menus", menus);
		return true;
	}

	/**
	 * 获取模型对象的错误信息，多个错误以换行符分开。
	 * 
	 * @param ar
	 * @return
	 * @throws Exception
	 */
	protected String getErrorMsg(ActiveRecordBase ar) throws Exception {
		String s = "";
		for (String err : ar.getErrors()) {
			s += err + "\n";
		}
		if (!s.equals("")) {
			s = s.substring(0, s.length() - 1);
		}
		return s;
	}
	
	public static String getIpAddr(HttpServletRequest request)  {   
	      String ip  =  request.getHeader( " x-forwarded-for " );   
	       if (ip  ==   null   ||  ip.length()  ==   0   ||   " unknown " .equalsIgnoreCase(ip))  {   
	          ip  =  request.getHeader( " Proxy-Client-IP " );   
	      }    
	       if (ip  ==   null   ||  ip.length()  ==   0   ||   " unknown " .equalsIgnoreCase(ip))  {   
	          ip  =  request.getHeader( " WL-Proxy-Client-IP " );   
	      }    
	       if (ip  ==   null   ||  ip.length()  ==   0   ||   " unknown " .equalsIgnoreCase(ip))  {   
	         ip  =  request.getRemoteAddr();   
	     }    
	      return  ip;   
	 }  

	protected RbacService rbac;

	protected boolean initRbac() throws Exception {
		rbac = new DefaultRbacService(request);
		if (rbac.getCurrentUser() == null) {
			String js = "var win=window;";
			js += "while(win.parent!=window.top){win=win.parent;}";
			js += "win.parent.location.href='" + request.getContextPath()
					+ "/home/login';";
			PrintWriter out = response.getWriter();
			out.println("<script>" + js + "</script>");
			out.close();
			// redirect("/home/login");
			return false;
		}
		User user = (User)rbac.getCurrentUser();
		Userlogin.keepUserLogin(user.getLogin(), getIpAddr(request));
		request.setAttribute("rbac", rbac);
		rbac.getCurrentCompPrivileges();
		return true;
	}

	protected boolean checkUserPrivilege() throws Exception {
		String actionUrl = controllerPath + "/" + actionName;
		boolean result = rbac.isAllowed(actionUrl);
		if (result == false) {
			redirect("/home/error/index");
			return false;
		}
		return true;
	}

	protected boolean isCreater(Integer UserId) throws Exception {
		User user = (User) rbac.getCurrentUser();
		return (user.getId() == UserId);
	}

	protected String loginUrl() throws Exception {
		User user = (User) rbac.getCurrentUser();
		return user.getLoginurl();
	}
	
	protected boolean isAdmin() throws Exception{
		User user = (User) rbac.getCurrentUser();
		String rolename = ","+user.getRoles()+",";
		if (rolename.indexOf("超级管理员") == -1)
			return false;
		else
		    return true;
	}

	// ///////////////////////////

	@SuppressWarnings("unchecked")
	protected List<Map<String, Object>> getTempFileList() throws Exception {
		List<Map<String, Object>> items = (List<Map<String, Object>>) session
				.getAttribute("TEMPFILES");
		if (items == null) {
			items = new ArrayList<Map<String, Object>>();
			session.setAttribute("TEMPFILES", items);
		}
		return items;
	}

	public View getTempFiles() throws Exception {
		List<Map<String, Object>> files = getTempFileList();
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("total", files.size());
		result.put("rows", files);
		return new JsonView(result);
	}

	public View uploadTempFile(MultipartFile file) throws Exception {
		if (!file.isEmpty()) {
			List<Map<String, Object>> items = getTempFileList();

			String fileName = file.getOriginalFilename();
			long fileSize = file.getSize();
			byte[] data = file.getBytes();

			boolean exists = false;
			for (Map<String, Object> item : items) {
				String fn = (String) item.get("fileName");
				if (fn.equalsIgnoreCase(fileName)) {
					item.put("fileName", fileName);
					item.put("fileSize", fileSize);
					item.put("data", data);
					exists = true;
					break;
				}
			}
			if (!exists) {
				Map<String, Object> newItem = new HashMap<String, Object>();
				newItem.put("fileName", fileName);
				newItem.put("fileSize", fileSize);
				newItem.put("data", data);
				items.add(newItem);
			}
		}
		View view = new JsonView("success:true");
		view.setContentType("text/plain;charset=utf-8");
		return view;
	}
}
